import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';

class RandomWords extends StatefulWidget {
  @override
  createState() => _RandomWordsState();
}

class _RandomWordsState extends State<RandomWords> {
  // 用于存储单词list
  final _suggestions = List<WordPair>();

  // 单词的字体大小
  final _biggerFont = const TextStyle(fontSize: 15.0, color: Colors.lightBlue);

  // 收藏的单词set
  final _saved = Set<WordPair>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('flutter'),
        elevation: 1.0,
        centerTitle: true,
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.list),
            onPressed: () {
              _pushSaved();
            },
          )
        ],
      ),
      body: _buildSuggestions(),
    );
  }

  // 构造显示单词对列表的listview
  Widget _buildSuggestions() {
    return ListView.builder(
//        padding: EdgeInsets.all(16.0),
        padding: EdgeInsets.all(16.0),
        itemBuilder: (context, i) {
          // 如果是奇数行就加一个分割线
          if (i.isOdd) {
            return new Divider();
          }
          final index = i ~/ 2;
          // 如果索引的值大于等于list的长度就会自动增加10个随机单词
          if (index >= _suggestions.length) {
            _suggestions.addAll(generateWordPairs().take(10));
          }
          return _buildRow(_suggestions[index]);
        });
  }

  Widget _buildRow(WordPair pair) {
    final alreadySaved = _saved.contains(pair);

    return ListTile(
      title: Text(
        pair.asPascalCase,
        style: _biggerFont,
      ),
      trailing: Icon(
        alreadySaved ? Icons.favorite : Icons.favorite_border,
        color: alreadySaved ? Colors.redAccent : null,
      ),
      onTap: () {
        setState(() {
          if (alreadySaved) {
            _saved.remove(pair);
          } else {
            _saved.add(pair);
          }
        });
      },
    );
  }

  void _pushSaved() {
    Navigator.of(context).push(
      new MaterialPageRoute(
        builder: (context) {
          final tiles = _saved.map(
            (pair) {
              return new ListTile(
                title: new Text(
                  pair.asPascalCase,
                  style: _biggerFont,
                ),
              );
            },
          );
          final divided = ListTile.divideTiles(
            context: context,
            tiles: tiles,
          ).toList();
          return Scaffold(
            appBar: AppBar(
              title: Text("saved suggestions"),
            ),
            body: new ListView(children: divided),
          );
        },
      ),
    );
  }
}
